import React, { useEffect, useState } from "react";
import {
  Button,
  Card,
  Col,
  Form,
  Input,
  message,
  Row,
  Select,
  Space,
  Table,
} from "antd";
import { PlusOutlined, SearchOutlined, SyncOutlined } from "@ant-design/icons";
import { getUserPage, saveUser, updateUser } from "@/api/user";
import PermissionButton from "@/components/PermissionButton";
import type { Page, User, UserPageDTO, UserSaveDTO, UserUpdDTO } from "@/types";

const UserManagement: React.FC = () => {
  const [users, setUsers] = useState<Page<User>>({
    records: [],
    total: 0,
    size: 10,
    current: 1,
    pages: 0,
  });

  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();

  const fetchUsers = async (
    params: UserPageDTO = { currentPage: 1, pageSize: 10 },
  ) => {
    setLoading(true);
    try {
      const res = await getUserPage(params);
      if (res.success) {
        setUsers(res.data);
      } else {
        message.error(res.msg);
      }
    } catch (error) {
      message.error("获取用户列表失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  const handleSearch = (values: any) => {
    fetchUsers({
      currentPage: 1,
      pageSize: 10,
      ...values,
    });
  };

  const handleReset = () => {
    searchForm.resetFields();
    fetchUsers();
  };

  const handleTableChange = (pagination: any) => {
    fetchUsers({
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm.getFieldsValue(),
    });
  };

  const showModal = (user?: User) => {
    if (user) {
      setEditingUser(user);
      form.setFieldsValue(user);
    } else {
      setEditingUser(null);
      form.resetFields();
    }
    setModalVisible(true);
  };

  const handleCancel = () => {
    setModalVisible(false);
    form.resetFields();
  };

  const handleSubmit = async (values: any) => {
    try {
      let res;
      if (editingUser) {
        const data: UserUpdDTO = {
          id: editingUser.id,
          ...values,
        };
        res = await updateUser(data);
      } else {
        const data: UserSaveDTO = values;
        res = await saveUser(data);
      }

      if (res.success) {
        message.success(`${editingUser ? "更新" : "创建"}用户成功`);
        setModalVisible(false);
        form.resetFields();
        fetchUsers();
      } else {
        message.error(res.msg);
      }
    } catch (e) {
      console.log(e);
      message.error(`${editingUser ? "更新" : "创建"}用户失败`);
    }
  };

  const columns = [
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
    },
    {
      title: "真实姓名",
      dataIndex: "realName",
      key: "realName",
    },
    {
      title: "手机号",
      dataIndex: "phone",
      key: "phone",
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: number) => <span>{status === 1 ? "启用" : "禁用"}</span>,
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: User) => (
        <Space>
          <PermissionButton
            type="link"
            size="small"
            permission="user:update"
            onClick={() => showModal(record)}
          >
            编辑
          </PermissionButton>
          <PermissionButton
            type="link"
            size="small"
            danger
            permission="user:delete"
            onClick={() => console.log("删除", record)}
          >
            删除
          </PermissionButton>
        </Space>
      ),
    },
  ];

  return (
    <Card
      title="用户管理"
      extra={
        <PermissionButton
          type="primary"
          icon={<PlusOutlined />}
          permission="user:create"
          onClick={() => showModal()}
        >
          新增用户
        </PermissionButton>
      }
    >
      <Form form={searchForm} layout="vertical" onFinish={handleSearch}>
        <Row gutter={24}>
          <Col span={6}>
            <Form.Item name="username" label="用户名">
              <Input placeholder="请输入用户名" />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="realName" label="真实姓名">
              <Input placeholder="请输入真实姓名" />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="phone" label="手机号">
              <Input placeholder="请输入手机号" />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="status" label="状态">
              <Select placeholder="请选择状态">
                <Select.Option value={1}>启用</Select.Option>
                <Select.Option value={0}>禁用</Select.Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={24} className="text-right">
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                icon={<SearchOutlined />}
              >
                查询
              </Button>
              <Button
                htmlType="button"
                onClick={handleReset}
                icon={<SyncOutlined />}
              >
                重置
              </Button>
            </Space>
          </Col>
        </Row>
      </Form>

      <Table
        className="mt-6"
        dataSource={users.records}
        columns={columns}
        loading={loading}
        pagination={{
          current: users.current,
          pageSize: users.size,
          total: users.total,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
        onChange={handleTableChange}
        rowKey="id"
      />
    </Card>
  );
};

export default UserManagement;
